package com.server.common.code.utils;

import com.server.common.code.error.BusinessException;
import com.server.common.code.http.HttpState;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

@Getter
@Setter
@Slf4j
public class ResultUtil {

    private static <T> Result<T> builder(T data, int code, String msg){
        Result<T> result = new Result<>();
        result.setData(data);
        result.setMsg(msg);
        result.setCode(code);
        return result;
    }

    public static <T> Result<T> successData(T data){
        return builder(data,HttpState.OK,HttpState.OK_STR);
    }

    public static Result<Void> successMsg(String msg){
        return builder(null,HttpState.OK,msg);
    }

    public static <T> Result<T> success(T data, String msg){
        return builder(data,HttpState.OK,msg);
    }

    public static Result<Void> success(){
        return builder(null,HttpState.OK,HttpState.OK_STR);
    }

    public static Result<Void> error(String msg){
        return builder(null,HttpState.ERROR,msg);
    }

    public static Result<Void> error(int code, String msg){
        return builder(null,code,msg);
    }

    public static Result<Void> error(){
        return builder(null,HttpState.ERROR, HttpState.ERROR_STR);
    }

    /**
     * 抛出异常，没有异常返回data
     * @author LXC
     * @date 2022/11/7 18:45
     */
    public static <T> T getDataThrowException(Result<T> result){
        if(200 != result.getCode()){
            throw new BusinessException(result.getMsg());
        }
        return result.getData();
    }

    /**
     * 不抛出异常,有异常返回data
     * @author LXC
     * @date 2022/11/7 18:46
     */
    public static <T> T getDataNotThrowException(Result<T> result){
        if(200 != result.getCode()){
            log.error("获取失败getData-"+ result.getMsg());
        }
        return result.getData();
    }
}
